package com.lc.stock.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.lc.stock.common.Constant;
import com.lc.stock.common.MairuiRetCode;
import com.lc.stock.exception.ResultException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author lichen
 * @description
 * @menu
 * @date 2023/2/3 16:18
 */
@Slf4j
@Component
public class HttpClientUtil {

    //缓存
    @Autowired
    private CacheManager cacheManager;

    @Value("${cache_stock}")
    private String cache_stock;
    /**
     * 拼合 http 参数
     * @param httpUrl
     * @param parms
     * @return
     */
    public String spliceParm(String httpUrl,List<String> parms){
        for (String str : parms) {
            httpUrl += "/" + str;
        }
        return httpUrl;
    }

    /**
     * 发送http get 请求
     * 根据配置的Lincese 间隔3秒循环调用
     * @param httpUrl
     * @param parms
     * @return
     */
    public String get(String httpUrl,String... parms)throws Exception {
        try{
            //把参数转成List
            List<String> parmList = Arrays.asList(parms);

            String resp = null;
            //从缓存中获取可用的licence
            Cache cache = cacheManager.getCache(cache_stock);
            JSONArray jsonArray = JSONArray.parseArray(cache.get(Constant.licence_key, String.class));

            List<String> removeLinceseList = new ArrayList<>();

            //循环调用API,直至调用成功
            for (Object o : jsonArray) {
                String license = (String) o;
                ArrayList<String> _parmList = new ArrayList<>();
                _parmList.addAll(parmList);
                _parmList.add(license);
                resp = HttpUtil.get(spliceParm(httpUrl, _parmList));

                if(StrUtil.isBlank(resp) || resp.equals("[]") || resp.equals("{}")){
                    log.error("调用的API" + httpUrl + "，参数："  + _parmList.toString() + "返回值为空");
                    Thread.sleep(3000);
                    continue;
                }
                if(null != MairuiRetCode.findByCode(resp)){
                    //当lincese 当日请求超限时，把超限的lincese从初始化的集合中删除掉
                    MairuiRetCode byCode = MairuiRetCode.findByCode(resp);
                    if(byCode.getCode().equals("101")){
                        removeLinceseList.add(license);
                    }
                    continue;
                }
                break;
            }

            //删除已经超限的lincese
            if(CollUtil.isNotEmpty(removeLinceseList)){
                removeLinceseList.forEach(str -> jsonArray.remove(str));
            }

            //所有的lincese 使用完毕后依然请求报错
            MairuiRetCode byCode = MairuiRetCode.findByCode(resp);
            if(null != byCode){
                throw new ResultException(Integer.parseInt(byCode.getCode()), byCode.getMsg());
            }
            return resp;
        }catch(ResultException e){
            throw e;
        }catch(Exception e){
            throw e;
        }
    }

}
